<?php

namespace app\admin\controller;

use app\common\model\ShopGroup;
use app\common\model\ShopGroupUser;
use app\common\model\ShopStore;
use think\Controller;
use buildView\Form;
use buildView\Grid;
use app\common\service\Status;
use app\common\model\ShopCoupon;
use app\common\model\ShopCouponRecord;
use buildView\Button;

/**
 * 优惠券管理
 * Class Coupon
 * @package app\admin\controller
 */
class Coupon extends Controller
{
    /**
     * 列表
     * @auth true
     * @menu true
     * @return string
     */
    public function index()
    {
        $store = session('store');
        $grid = new Grid(new ShopCoupon);
        if ($store){
            $grid->model()->where('store_id',$store['id']);
        }else{
            $grid->store()->name('类型')->display(function ($val,$data){
                if ($val){
                    return $val;
                }else{
                    $html = "平台";
                    return $html;
                }
            });
        }
        $grid->column('title','优惠券名称');
        $grid->column('info','优惠券信息')->display(function ($val,$data){
            $html = "满 {$data['condition_price']} 减 {$data['cut_price']}";
            return $html;
        })->width(200)->align('center');
        $grid->column('time','有效期时间')->display(function ($val,$data){
            $html = "{$data['start_time']} -  {$data['end_time']}";
            return $html;
        })->width(200)->align('center');
        $grid->column('status', '状态')->using(Status::ACTIVITYSTATUS())->badge();
		$grid->column('create_at','添加时间');
		$grid->filter(function ($filter){
            $filter->dateBetween('start_time','开始时间');
            $filter->dateBetween('create_at','添加时间');
        });

        $grid->hideExportButton();
        $grid->actions(function ($action, $data){
            $button = new Button('使用记录','warm');
            $button->href(url('record') ."?cid={$data['id']}");
            $action->prepend($button);
            $button = new Button('优惠券发放','normal');
            $button->href(url('grant') ."?cid={$data['id']}");
            $action->prepend($button);
            $action->hideDetail();
        });
        return $grid->view();
    }

    /**
     * 添加/编辑
     * @auth true
     * @menu true
     * @return string
     */
    public function form()
    {
        $store = session('store');
        if ($store){
            $store_id = $store['id'];
        }else{
            $store_id = 0;
        }
        $form = new Form(new ShopCoupon);
        $form->text('title','优惠券名称')->required();
        $form->number('condition_price','需满足金额')->required();
		$form->number('cut_price','满减金额')->required();
		$form->date('start_time','开始时间')->help('优惠券有效期开始时间')->required();
		$form->date('end_time','结束时间')->help('优惠券有效期结束时间')->required();
        $form->hidden('store_id','门店id')->default($store['id']);
        $form->saving(function ($post) {
            if ($post['end_time'] < $post['start_time']) {
                $this->error('结束时间不能早于开始时间', '');
            }
            $time = date('Y-m-d H:i:s');
            $start_time = $post['start_time'];
            $end_time = $post['end_time'];
            if ($start_time > $time && $end_time >= $time) {
                $post['status'] = 0;
            } elseif ($start_time < $time) {
                $post['status'] = 1;
            } elseif ($end_time < $time) {
                $post['status'] = 2;
            }
            return $post;
        });
        return $form->view();
    }

    /**
     * 优惠券发放
     * @auth true
     * @menu true
     * @return string
     */
    public function grant()
    {
        $store = session('store');
        $cid = $this->request->get('cid');
        $form = new Form(new ShopCouponRecord);
        $event  = <<<EOF
            let value = $('[name=type]').val();
            if(value == 1){
                $('[name=user]').parent().parent().parent().parent().hide();
                $('[name=store]').parent().parent().show();
            }else{
                 $('[name=user]').parent().parent().parent().parent().show();
                $('[name=store]').parent().parent().hide();
            }
EOF;
        $form->script($event);
        if ($store){
            $user = \app\common\model\User::where('store_id',$store['id'])->select()->column('search_tip','id');
            $form->select('type','类型')->options([
                2=>'用户',
            ])->event($event)->default(2);
            $form->select('user','用户')->options($user)->multiple();
        }else{
            $user = \app\common\model\User::select()->column('search_tip','id');
            $form->select('type','类型')->options([
                1=>'门店',
                2=>'用户'
            ])->event($event)->default(2);
            $form->select('user','用户')->options($user)->multiple();
            $store = ShopStore::where('status',1)->where('is_deleted',0)->column('name','id');
            $form->select('store','门店')->options($store);
//            $group = ShopGroup::select()->column('name','id');
//            $form->select('group','用户组')->options($group);
        }
        $form->hidden('coupon_id','')->default($cid);
        $form->saving(function($post){
            if ($post['type'] == 2){
                if ($post['user']){
                    $user = explode(',',$post['user']);
                    $data = [];
                    foreach ($user as $key => $val){
                        $data[] =[
                            'coupon_id' => $post['coupon_id'],
                            'uid' => $val
                        ];
                    }
                    (new ShopCouponRecord)->saveAll($data);
                    return $post;
                }else{
                    $this->error('请选择用户');
                }
            }
            if ($post['type'] == 1){
                if ($post['store']){
                    $group = \app\common\model\User::where('store_id',$post['store'])->select()->toArray();
                    if ($group){
                        $group_user = [];
                        foreach ($group as $key => $value){
                            $group_user[] =[
                                'coupon_id' => $post['coupon_id'],
                                'uid' => $value['id']
                            ];
                        }
                        (new ShopCouponRecord)->saveAll($group_user);
                    }
                    return $post;
                }else{
                    $this->error('请选择门店');
                }
            }
        });
//        $form->saved(function ($post,$model){
//           ShopCouponRecord::where('id',$model->id)->delete();
//        });
        return $form->view();
    }

    /**
     * 领取记录
     * @auth true
     * @menu true
     * @return string
     */
    public function record()
    {
        $cid = $this->request->get('cid');
        $grid = new Grid(new ShopCouponRecord);
        $grid->model()->where('coupon_id', $cid)->select();
		$grid->user()->userInfo();
		$grid->column('type','使用状态')->using(Status::USETYPE())->badge();
		$grid->column('use_time','使用时间');
		$grid->column('create_at','领取时间');
		$grid->filter(function ($filter){
             $filter->eq('type','使用状态')->select(Status::USETYPE());
            $filter->dateBetween('create_at','领取时间');
        });
        $grid->hideAction();
        $grid->hideAddButton();
        $grid->hideExportButton();
        $grid->hideExportButton();
        $grid->actions(function ($action){
        });
        return $grid->view();
    }
}
